package com.example.demo.leetcode.classics150;

import java.util.HashMap;
import java.util.Map;

/**
 * ******************************************************
 *
 * @author liugh9
 * @version 1.0
 * @classname _27两数之和II输入有序数组
 * @description
 * @date 2023/07/16 8:55
 * <p>
 * ******************************************************
 */
public class _27两数之和II输入有序数组 {

    public int[] twoSum1(int[] numbers, int target) {
        int i = 0, j = numbers.length - 1;
        int sum = 0;

        while (i < j) {
            sum = numbers[i] + numbers[j];
            if (sum < target) {
                i++;
            } else if (sum > target) {
                j--;
            } else {
                return new int[]{i + 1, j + 1};
            }
        }
        return null;
    }

    public int[] twoSum(int[] numbers, int target) {
        Map<Integer, Integer> valueToIndex = new HashMap<>();

        for (int k = 0; k < numbers.length; k++) {
            if (valueToIndex.containsKey(numbers[k])) {
                return new int[]{valueToIndex.get(numbers[k]) + 1, k + 1};
            } else {
                valueToIndex.put(target - numbers[k], k);
            }
        }
        return null;
    }
}
